package com.learn.springbootnetty.字节流和字符流;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author xiaodonghong
 * @description TODO
 * @date 2023/6/19-10:18
 */
public class BufferedOutputStream extends FilterOutputStream {
    protected byte buf[]; // 缓冲区字节数组

    protected int count; // 记录每次写入的字节数量

    public BufferedOutputStream(OutputStream out) {
        this(out, 8192);
    }

    public BufferedOutputStream(OutputStream out, int size) {
        super(out);
        if (size <= 0) {
            throw new IllegalArgumentException("Buffer size <= 0");
        }
        buf = new byte[size];
    }

    private void flushBuffer() throws IOException {
        if (count > 0) {
            out.write(buf, 0, count); // out 即传入的输出流，即 FileOutputStream
            count = 0;
        }
    }

    @Override
    public synchronized void write(int b) throws IOException {
        if (count >= buf.length) { // 到达 8k 大小就进行 IO
            flushBuffer();
        }
        buf[count++] = (byte) b; // 在没达到缓冲区指定大小时，没有做 IO
    }

    @Override
    public synchronized void flush() throws IOException {
        flushBuffer(); // 主动 IO
        out.flush();
    }
}

